function generateCanvas(keyForReplacement) {
    var bootstrapLink = $("#bootstrap");
    var checkedBoxes = $("input:checkbox:checked");
    if (checkedBoxes.length == 0) {
        alert("Please choose the student(s) for the achievement");
        return;
    }
    var achievementType = $("#type");
    var radio = $(":radio:checked");
    if (achievementType.val() === "? undefined:undefined ?" ||
        (achievementType.val() === "earned" && radio.val() === undefined)) {
        alert("Please define achievement type");
        return;
    }
    bootstrapLink.attr('href', '');
    html2canvas($(".acheivement"), {
        onrendered: function (canvas) {
            var studentIds = '';
            var i = 1;
            $(checkedBoxes).each(function(){
                studentIds = studentIds + encodeURIComponent($(this).val());
                if (i < checkedBoxes.length) {
                    studentIds = studentIds + '@';//use this character as ampersand as it is not usable in an email account
                    i++;
                }
            });
            var textBoxes = $(".gwt-TextBox");
            var ajaxUrl = '/ajax/processor?command=addAchievement'+
                '&fakeName=' + $(textBoxes[1]).val() +
                '&status=' + achievementType.val() +
                '&studentId=' + studentIds +
                (radio.val() !== undefined ? '&isPositive=' + radio.val() : '') +
                (keyForReplacement === '' || keyForReplacement === undefined ? '' : '&replace=' + keyForReplacement) +
                '&imageSrc=' + encodeURIComponent($(textBoxes[0]).val());
            $.ajax({
                type: 'POST',
                url: ajaxUrl,
                data: 'image='+canvas.toDataURL(),
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                processData: 'false',
                success: function(msg) {
                    angular.element('[ng-controller=GWTDivController]').scope().releaseReplace();
                    angular.element('[ng-controller=GWTDivController]').scope().$apply();
                    alert('Image generated successfully');
                },
                error: function(msg) {
                    var jsonData = JSON.parse(msg);
                    alert(jsonData['error']);
                }
            });
            $("#bootstrap").attr('href', '../css/bootstrap.css');
        }
    });
}

//remove broken link on the bottom of the page
function normalizeGWTButtons() {
    var lowestRowTr = $("#main .gwt-Image").parent("td").parent("tr");
    $("#main .gwt-Image").remove();
    var buttons = $("#main .acheivement-button");
    var lastButton = buttons.last();
    lastButton.parent("td").attr('align', 'center');
    var clickFunction = function() {
        generateCanvas(angular.element('[ng-controller=GWTDivController]').scope().replaceKey);
    }
    lastButton.on('click', clickFunction);
    var lowestRow = $(buttons.last()).parent("td");
    lowestRow.prepend('<span class="acheivement-title">Choose achievement type: ' +
        '</span>&nbsp;' +
        '<div style="display:inline" ng-controller="AchievementTypeListController"><select class="dropdown" ng-model="typesList" id="type">' +
        '<option ng-repeat="atype in types" value="{{atype.type}}" ng-selected="selectedType === atype.type">{{atype.name}}</option>' +
        '</select>' +
        '<div style="display:inline; padding-left: 5px" ng-animate ng-show="typesList==\'earned\' || selectedType == \'earned\'">' +
            '<label ng-repeat="effect in effects"><input type="radio" name="effect" value="{{effect.type}}" ' +
        'ng-checked=" isPositive == effect.type">' +
            '{{effect.name}} &nbsp;</label></div></div>'
    );
    lowestRowTr.attr('ng-show', 'replaceKey !== \'\' && replaceKey !== undefined');
    var lowestCell = lowestRowTr.children("td");
    lowestCell.attr('align', 'middle');
    lowestCell.html('You are now replacing another achievement. ' +
    '<a href="javascript:void(0)" ng-click="releaseReplace()">Click here</a> to continue without overriding it.');
    var secondRow = $("#main .mainPanel").children("tbody").children("tr:nth-child(2)");
    secondRow.after('<tr><td align="center"><span class="acheivement-title">' +
        'Choose students for achievement' +
        '</span> </td></tr>'+
        '<tr ng-controller="StudentListController">' +
        '<td align="center" padding-left="5px" class="acheivement-editorLabel">' +
        '<label ng-repeat="stud in students"><input type="checkbox" value="{{stud.nickname}}" ' +
        'ng-checked="replaceId === stud.nickname" ng-disabled="replaceId !== \'\' && replaceId !== undefined"/>' +
        '{{stud.fullname}} &nbsp;</label>' +
        '</td></tr>');
    var angularElement = angular.element('#main').scope().recompile();
    var achievementButton = $("#main .acheivement-button").first();
    var srcIcon = $(".acheivement-icon");
    $(achievementButton).off('click').on('click',function() {
        $.ajax({
            type: 'POST',
            contentType: 'application/x-www-form-urlencoded',
            url: '/ajax/processor?command=decodeImage&query='+ encodeURIComponent($(".gwt-TextBox").first().val()),
            success: function(data) {
                var datajson = JSON.parse(data);
                $(srcIcon).attr('src', datajson['image']);
            },
            error: function(data) {
                var datajson = JSON.parse(data);
                alert("Japaneze penis very small " + datajson['error']);
            }
        })
    });
}

window.onload = function() {
    if (navigator.appName='Netscape') {
        window.onload = setTimeout("normalizeGWTButtons()", 500);
    } else {
        window.onload = normalizeGWTButtons();
    }
};

function replaceUrl(picUrl, picTitle){
    $(".acheivement-icon").prop('src', '');
    var textBoxes = $(".gwt-TextBox");
    var imageTextBox = $(textBoxes[0]);
    imageTextBox.val(picUrl);
    $(textBoxes[1]).val(picTitle);
    $(textBoxes[1]).trigger("keypress");
    var achievementButton = $("#main .acheivement-button").first();
    achievementButton.trigger("click");
}

